package cn.qingyun.gis.modules.baogan.service.impl;

import cn.qingyun.gis.modules.baogan.entity.MicroStreetData;
import cn.qingyun.gis.modules.baogan.enums.OperationTypeEnum;
import cn.qingyun.gis.modules.baogan.enums.SceneTypeEnum;
import cn.qingyun.gis.modules.baogan.service.MicroStreetDataService;
import cn.qingyun.gis.modules.baogan.vo.request.ReviewRequest;
import cn.qingyun.gis.modules.init.system.vo.LoginUser;
import cn.qingyun.gis.modules.init.utils.SystemUtil;
import cn.qingyun.gis.modules.scenes.contant.ReviewEnum;
import cn.qingyun.gis.modules.scenes.entity.UniAddrRegion;
import cn.qingyun.gis.modules.scenes.service.IUniAddrRegionService;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import cn.qingyun.gis.modules.baogan.mapper.MicroStreetAuditLogMapper;
import cn.qingyun.gis.modules.baogan.entity.MicroStreetAuditLog;
import cn.qingyun.gis.modules.baogan.service.MicroStreetAuditLogService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@DS("scenes_offensive")
@Slf4j
@Service
public class MicroStreetAuditLogServiceImpl extends ServiceImpl<MicroStreetAuditLogMapper, MicroStreetAuditLog> implements MicroStreetAuditLogService {

    @Resource
    private MicroStreetAuditLogMapper microStreetAuditLogMapper;
    @Resource
    private MicroStreetDataService microStreetDataService;
    @Resource
    private IUniAddrRegionService uniAddrRegionService;

    @Transactional
    @Override
    public Integer review(ReviewRequest request) {
        log.info("审核的id={}", request.getId());
        Integer reviewState = request.getReviewState();
        LoginUser currentUser = SystemUtil.getCurrentUser();
        if (Objects.isNull(currentUser)){
            throw new RuntimeException("解析用户失败");
        }
        Date now = new Date();
        //查询原审核信息，获取操作状态
        MicroStreetAuditLog oldLog = microStreetAuditLogMapper.selectOneByStreetId(request.getId());
        Integer operationType = oldLog.getOperationType();
        String wktString = oldLog.getNewWkt();
        //更新审核表
        MicroStreetAuditLog auditLog = MicroStreetAuditLog.builder()
                .reviewer(currentUser.getUsername())
                .reviewRemark(request.getReviewRemark())
                .reviewState(reviewState)
                .reviewTime(now)
                .streetId(request.getId())
                .reviewPhone(currentUser.getPhone())
                .build();
        QueryWrapper<MicroStreetAuditLog> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(MicroStreetAuditLog::getStreetId, request.getId())
                .eq(MicroStreetAuditLog::getReviewState, ReviewEnum.REVIEWED.getCode());
        int update = microStreetAuditLogMapper.update(auditLog, wrapper);

        //变更基础数据表
        if (Objects.equals(ReviewEnum.PASS.getCode(), reviewState)) {//通过
            MicroStreetData streetData = new MicroStreetData();
            //将数据保存到路网表中
            if (operationType.equals(OperationTypeEnum.ADD.getCode())){//新增
                streetData.setWkt(wktString);
                streetData.setUpdateTime(now);
                streetData.setUpdateBy(oldLog.getCreateBy());
                streetData.setCreateTime(oldLog.getCreateTime());
                streetData.setCreateBy(oldLog.getCreateBy());
                streetData.setWorkNo(oldLog.getCreateId());
                streetData.setPhone(oldLog.getCreatePhone());
                streetData.setProtractFlag(1);
                streetData.setMicroGridName(oldLog.getMicroGridName());
                streetData.setMicroGridName(oldLog.getMicroGridCode());
                UniAddrRegion uniAddrRegion = uniAddrRegionService.getGridName(oldLog.getMicroGridCode());
                streetData.setGridCode(uniAddrRegion.getParentCode());
                streetData.setGridName(uniAddrRegion.getParentName());
                streetData.setName(oldLog.getName());
                streetData.setType(SceneTypeEnum.STREET_SHOP.getDesc());
                microStreetDataService.saveBoundary(streetData);
            }else if (operationType.equals(OperationTypeEnum.UPDATE.getCode())){//修改
                streetData.setWkt(wktString);
                streetData.setId(oldLog.getStreetId());
                streetData.setUpdateTime(now);
                streetData.setUpdateBy(oldLog.getCreateBy());
                microStreetDataService.updateWKT(streetData);
            } else if (operationType.equals(OperationTypeEnum.DELETE.getCode())) {//删除
                QueryWrapper<MicroStreetData> wrapper1 = new QueryWrapper<>();
                wrapper1.lambda().eq(MicroStreetData::getId, oldLog.getStreetId());
                microStreetDataService.remove(wrapper1);
            }
        }else {//驳回
            if (operationType.equals(OperationTypeEnum.ADD.getCode())){//todo 新增，考虑删除这个面的看管信息，这个面的parentID信息
                //查询基础数据表
                MicroStreetData streetData = microStreetDataService.selectOneById(request.getId());
                if (streetData.getProtractFlag().equals(1)){//圈画
                    //将父Id 设置为空
                    List<String> pointIds = microStreetDataService.selectPointInPolygon(oldLog.getNewWkt());
                    microStreetDataService.updateParentIdNullById(pointIds,streetData.getId());
                }
                if (streetData.getProtractFlag().equals(2)){//绘制面
                    //直接删除
                    microStreetDataService.removeById(streetData.getId());
                }
            }

        }
        return update;
    }

    @Override
    public boolean adjustBoundary(MicroStreetAuditLog record) {
        return this.baseMapper.adjustBoundary(record);
    }

    @Override
    public void addAuditLog(MicroStreetAuditLog record) {
         this.baseMapper.addAuditLog(record);
    }

    @Override
    public MicroStreetAuditLog selectAuditLogByStreetId(String streetId) {
        QueryWrapper<MicroStreetAuditLog> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(MicroStreetAuditLog::getStreetId,streetId);
        return this.baseMapper.selectOne(wrapper);
    }

    @Override
    public void updateByStreetId(MicroStreetAuditLog record) {
        microStreetAuditLogMapper.updateByStreetId(record);
    }
}
